var util = require('../../libs/util.js');
//获取应用实例
var app = getApp()
var moment = require('../../libs/moment.min.js');
moment.locale('zh-cn');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    pageSize: 10,
    pageNumber: 0,
    count: 0,
    page: 1,
    firstPage: true,
    prevPage: true,
    nextPage: true,
    lastPage: true,
    mode: 'income',
    formula: '',
    start_date: moment().format('YYYY-MM-DD'),
    end_date: moment().format('YYYY-MM-DD'),
    priceTypeList: [
      { name: '公式',type:"formulaprice", value: '2', checked: true },
      { name: '单位',type:"unitprice", value: '1' },
      { name: '一口价', type: "oneprice", value: '0' }
    ],
    priceType:'formulaprice',
    warehouse: '请选择发货点（仓库）',
    formType:'add',
    vehicleLength:[],
    vehicleLengthIndex: -1,
    vehicleFunction: [],
    vehicleFunctionIndex: -1,
    vehicleSource: [],
    vehicleSourceIndex: -1
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    if (e.id) {
      this.setData({
        id: e.id
      })
    }
    this.loadVehicleProperty();
    this.loadData();
  },
  priceTypeChange: function (e) {
    console.log(e.detail.value);
  
    var priceTypeList = this.data.priceTypeList, values = e.detail.value;
    var priceType = 'unitprice';
    for (var i = 0, lenI = priceTypeList.length; i < lenI; ++i) {
      priceTypeList[i].checked = false;

      for (var j = 0, lenJ = values.length; j < lenJ; ++j) {
        if (priceTypeList[i].value == values[j]) {
          priceTypeList[i].checked = true;
          priceType = priceTypeList[i].type;
          break;
        }  
      }
    }

    this.setData({
      priceTypeList: priceTypeList,
      priceType: priceType
    });
  },
  bindInput: function (e) {
    var that = this;
    var item = String(e.currentTarget.id), item_value = {};
    var value = e.detail.value;

    var inputtype = e.currentTarget.dataset.inputtype;
    if (inputtype == 'digit' || inputtype == 'number') {
      if (isNaN(value)) {
        value = '';
      }
    }
    item_value[item] = value;
    that.setData(item_value);
  },
  search: function () {
    this.loadData();
  },
  //切换收入或支出
  changeMode: function (e) {
    this.setData({
      mode: e.currentTarget.dataset.mode
    })
    this.loadData();
  },
  //获取车辆属性
  loadVehicleProperty: function () {
    wx.showLoading({
      title: '加载车辆属性...',
      mask: true
    })
    var that = this;
    util.getData("/atapi/vehicle/vehicle/property", {}, function (res, error) {
      console.log(res); console.log(error)
      if (res.data.success) {
        var vehicleLength = res.data.vehicleLength.name;
        //vehicleLength.unshift('请选择');
        var vehicleLengthCode = res.data.vehicleLength.code;
        //vehicleLengthCode.unshift('');

        var vehicleFunction = res.data.vehicleFunction.name;
        //vehicleFunction.unshift('请选择');
        var vehicleFunctionCode = res.data.vehicleFunction.code;
        //vehicleFunctionCode.unshift('');

        var vehicleSource = res.data.vehicleSource.name;
        //vehicleSource.unshift('请选择');
        var vehicleSourceCode = res.data.vehicleSource.code;
        //vehicleSourceCode.unshift('');

        that.setData({
          vehicleLength: vehicleLength,
          vehicleFunction: vehicleFunction,
          vehicleSource: vehicleSource,
          vehicleLengthCode: vehicleLengthCode,
          vehicleFunctionCode: vehicleFunctionCode,
          vehicleSourceCode: vehicleSourceCode
        }); 
      }
      that.loadData();
    });
  },
  loadData: function () {
    var that = this;
    wx.showLoading({
      title: '获取数据...',
      mask: true
    })
    util.getData("/atapi/price/price/shopPriceConfig", {
      'type': that.data.type,
      'shop': that.data.id,
      'searchVal': that.data.searchVal,
      'page': that.data.page,
      'pageSize': that.data.pageSize,
      'mode': that.data.mode,
      'CO_ID': app.globalData.CO_ID
    }, function (res, error) {
      console.log(res); console.log(error)
      if (res.data.success) {
        var count = res.data.data[1][0].COUNT;
        var pageNumber = Math.ceil(count / that.data.pageSize);
        var _data = res.data.data[0];
        for(var i=0;i<_data.length;i++){
          _data[i].vehicleLengthText = that.data.vehicleLength[_data[i].vehicleLength];
          _data[i].vehicleSourceText = that.data.vehicleSource[_data[i].vehicleSource];
          _data[i].vehicleFunctionText = that.data.vehicleFunction[_data[i].vehicleFunction];
        }
        that.setData({
          dataList: _data,
          count: count,
          pageNumber: pageNumber
        });
        that.setPageStatus();
      } else {
        that.setData({
          page: 0,
          dataList: []
        });
      }
      wx.hideLoading()
    });
  },
  //提交价格配置
  savePriceConfig: function () {
    var that = this;
    wx.showLoading({
      title: '数据合法检查中...',
      mask: true
    })
    var priceConfig = {};
    priceConfig.shop = that.data.id;
    priceConfig.mode = that.data.mode;
    priceConfig.type = that.data.priceType;
    priceConfig.CO_ID = app.globalData.CO_ID;
    priceConfig.user_id = app.globalData.user_id;

    priceConfig.start_date = that.data.start_date;
    priceConfig.end_date = that.data.end_date;

    priceConfig.formula = that.data.formula;
    
    priceConfig.vehicleLength = that.data.vehicleLengthCode[that.data.vehicleLengthIndex]||'';
    priceConfig.vehicleSource = that.data.vehicleSourceCode[that.data.vehicleSourceIndex] || '';
    priceConfig.vehicleFunction = that.data.vehicleFunctionCode[that.data.vehicleFunctionIndex] || '';

    if (priceConfig.formula == '') {
      wx.showToast({
        title: "价格未有设置",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }

    if (priceConfig.start_date == priceConfig.end_date) {
      wx.showToast({
        title: "日期相同",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    if (moment(priceConfig.start_date) > moment(priceConfig.end_date)) {
      wx.showToast({
        title: "开始大于结束",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    if (that.data.formType == 'edit') {
      priceConfig.id = that.data.pid
    }

    priceConfig.warehouse = that.data.warehouseId||'';
    if (priceConfig.warehouse == '') {
      wx.hideLoading()
      wx.showModal({
        title: '温馨提示',
        content: '发货点（仓库）未选择，确定设置为所有项目公用计价吗？',
        success(res) {
          if (res.confirm) {
            that.submitPriceConfig(priceConfig)
          }
        }
      });
    }else{
      that.submitPriceConfig(priceConfig)
    }
  },
  submitPriceConfig: function (priceConfig) {
    var that = this;
    wx.showLoading({
      title: '提交中...',
      mask: true
    })
    if (that.data.formType == 'add'){
      util.postData("/atapi/price/price/saveShopPriceConfig", priceConfig, function (res, error) {
        console.log(res); console.log(error)
        if (res.data.success) {
          wx.showToast({
            title: "提交成功",
            icon: "success",
            duration: 3000,
            success: function () {
              setTimeout(function () {
                that.hideModal();
                that.loadData();
              }, 3000);
            }
          });
        } else {
          wx.showToast({
            title: "提交失败",
            image: '/images/wrong.png',
            duration: 3000
          });
        }
        wx.hideLoading()
      });
    }else{
      util.putData("/atapi/price/price/editShopPriceConfig", priceConfig, function (res, error) {
        console.log(res); console.log(error)
        if (res.data.success) {
          wx.showToast({
            title: "修改成功",
            icon: "success",
            duration: 3000,
            success: function () {
              setTimeout(function () {
                that.hideModal();
                that.loadData();
              }, 3000);
            }
          });
        } else {
          wx.showToast({
            title: "修改失败",
            image: '/images/wrong.png',
            duration: 3000
          });
        }
        wx.hideLoading()
      });
    }
    
  },
  //删除价格配置
  deletePriceConfig: function (e) {
    var that = this;
    wx.showModal({
      title: '温馨提示',
      content: '确定删除吗？',
      success(res) {
        if (res.confirm) {
          var id = e.currentTarget.dataset.id;
          util.putData("/atapi/price/price/deleteShopPriceConfig", {
            'id': id,
            'CO_ID': app.globalData.CO_ID,
            'user_id': app.globalData.user_id
          }, function (res, error) {
            console.log(res); console.log(error)
            if (res.data.success) {
              wx.showToast({
                title: "删除成功",
                icon: "success",
                duration: 3000,
                success: function () {
                  setTimeout(function () {
                    that.hideModal();
                    that.loadData();
                  }, 3000);
                }
              });
            } else {
              wx.showToast({
                title: "删除失败",
                image: '/images/wrong.png',
                duration: 3000
              });
            }
          });
        }
      }
    })

  },
  editShopPrice: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    var dataList = that.data.dataList;
    var currentItem = {};
    for (var i = 0; i < dataList.length;i++){
      if (dataList[i].ID == id){
        currentItem = dataList[i];
        break;
      }
    }
    var priceType = currentItem.type, priceTypeList = that.data.priceTypeList;
    for (var i = 0; i < priceTypeList.length;i++){
      if (priceTypeList[i].type == priceType){
        priceTypeList[i].checked = true;
      }else{
        priceTypeList[i].checked = false;
      }
    }

    that.setData({
      pid:id,
      formula: currentItem.formula,
      start_date: currentItem.start_date,
      end_date: currentItem.end_date,
      priceType: currentItem.type,
      warehouseId: currentItem.warehouse||'',
      warehouse: currentItem.whName||'请选择发货点（仓库）',
      formType: 'edit',
      modalTitle:'修改价格配置',
      modalName:'viewModal',
      priceTypeList: priceTypeList
    })
  },
  //选择车辆属性
  PickerChange(e) {
    console.log(e);
    var type = e.currentTarget.dataset.type;
    if (type == 'length') {
      this.setData({
        vehicleLengthIndex: e.detail.value
      })
    }
    if (type == 'source') {
      this.setData({
        vehicleSourceIndex: e.detail.value
      })
    }
    if (type == 'function') {
      this.setData({
        vehicleFunctionIndex: e.detail.value
      })
    }
    if (type == 'price_priority_mode') {
      this.setData({
        price_priority_mode_index: e.detail.value
      })
    }
  },
  //翻页按钮状态
  setPageStatus: function () {
    var that = this;
    var page = that.data.page, pageNumber = that.data.pageNumber;
    if (pageNumber == 1) {
      that.setData({
        firstPage: true,
        prevPage: true,
        nextPage: true,
        lastPage: true
      });
    } else if (pageNumber > 1) {
      if (page == 1) {
        that.setData({
          firstPage: true,
          prevPage: true,
          nextPage: false,
          lastPage: false
        });
      } else if (page == pageNumber) {
        that.setData({
          firstPage: false,
          prevPage: false,
          nextPage: true,
          lastPage: true
        });
      } else if (page < pageNumber && page > 1) {
        that.setData({
          firstPage: false,
          prevPage: false,
          nextPage: false,
          lastPage: false
        });
      }
    }
  },
  //分页按钮操作
  pageChange: function (e) {
    var type = e.currentTarget.dataset.page;
    if (type == 'first') {
      this.setData({
        page: 1
      })
      this.loadData();
    }
    if (type == 'last') {
      this.setData({
        page: this.data.pageNumber
      })
      this.loadData();
    }
    if (type == 'prev') {
      this.setData({
        page: this.data.page - 1
      })
      this.loadData();
    }
    if (type == 'next') {
      this.setData({
        page: this.data.page + 1
      })
      this.loadData();
    }
  },
  showModal(e) {
    var that = this;
    this.setData({
      modalName: e.currentTarget.dataset.target,
      modalTitle: (that.data.mode == 'income' ? '收入' : '支出') + e.currentTarget.dataset.name,
      modalType: e.currentTarget.dataset.type,
      formula: '',
      start_date: moment().format('YYYY-MM-DD'),
      end_date: moment().format('YYYY-MM-DD'),
      warehouseId: '',
      warehouse: '请选择发货点（仓库）',
      formType: 'add',
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  changeWarehouse: function (e) {
    var that = this;
    wx.navigateTo({
      url: '/pages/schedule/monitor_warehouse'
    })
  },
  // ListTouch触摸开始
  ListTouchStart(e) {
    this.setData({
      ListTouchStart: e.touches[0].pageX
    })
  },

  // ListTouch计算方向
  ListTouchMove(e) {
    this.setData({
      ListTouchDirection: e.touches[0].pageX - this.data.ListTouchStart > 0 ? 'right' : 'left'
    })
  },

  // ListTouch计算滚动
  ListTouchEnd(e) {
    if (this.data.ListTouchDirection == 'left') {
      this.setData({
        modalName: e.currentTarget.dataset.target
      })
    } else {
      this.setData({
        modalName: null
      })
    }
    this.setData({
      ListTouchDirection: null
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    wx.getStorage({
      key: 'monitor_warehouse',
      success: function (res) {
        if (res.data) {
          that.setData({
            warehouse: String(res.data.abbreviation || res.data.name).substr(0, 10),
            warehouseId: res.data.value
          });
        }
      },
      complete: function (res) {
        wx.removeStorage({
          key: 'monitor_warehouse',
          success: function (res) {
          }
        });
      }
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})